import { Logger } from "@nestjs/common"
import { catchError, delay, retry, throwError, timer } from "rxjs"

export const PROTOCALREGEX = /^(.*?):\/\//

export function getDBType(url: any) {
    const matches = url.match(PROTOCALREGEX)

    const protocal = matches ? matches[1] : 'file'

    return protocal == 'file' ? 'sqlite': protocal
}

// 断线重连
export function handleRetry(retryAttempts: any, retryDelay: any) {
    const logger = new Logger('PrismaModule')

    return (source: any) => source.pipe(
        retry({
            count: retryAttempts < 0 ? Infinity : retryAttempts,
            delay: (error: any, retryCount: any) => {
                let attemps = retryAttempts < 0 ? Infinity : retryAttempts
                if(retryCount <= attemps) {
                    logger.error(
                        `Unable to connect  to the database.Retrying (
                        ${retryCount})...`,
                        error.stack
                    )

                    return timer(retryDelay)
                } else {
                    return throwError(() => new Error('Reached max retries'))
                }
            }
        }),
        catchError((error: any) => {
            logger.error(`Failed to connect to the database after retries ${retryAttempts} times`, error.stack || error)

            return throwError(() => error)
        })
    )
}